<template>
  <div>
    <a-form :model="form" @submit="save($event)" ref="formRef" autocomplete="off" :rules="rules">
      <!-- 新密码 -->
      <a-form-item name="newPassword">
        <a-input
          v-model:value="form.newPassword"
          :placeholder="l('Password')"
          autoFocus
          type="password"
        />
        <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
      </a-form-item>
      <!-- 重复输入新密码 -->
      <a-form-item name="passwordRepeat">
        <a-input
          v-model:value="form.passwordRepeat"
          :placeholder="l('PasswordRepeat')"
          type="password"
        />
        <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
      </a-form-item>
      <!-- 保存 -->
      <a-form-item>
        <a-row style="justify-content: space-between">
          <a-col :sapn="8">
            <a-button block type="primary" @click="save($event)" html-type="submit">
              {{ l('Submit') }}
            </a-button>
          </a-col>
          <a-col :sapn="8">
            <a-button block @click="Backlogin()">
              {{ l('Back') }}
            </a-button>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
  import {
    AccountServiceProxy,
    ResetPasswordOutput,
    ResetPasswordInput,
  } from '/@/shared/service-proxies/service-proxies';
  import { defineComponent } from 'vue';
  import { appSessionService } from '/@/shared/abp';
  import { AppComponentBase } from '/@/shared/component-base';
  import { ResetPasswordModel } from './reset-password.model';

  export default defineComponent({
    name: 'reset-password',
    mixins: [AppComponentBase],
    data() {
      return {
        form: {
          newPassword: '',
          passwordRepeat: '',
        },
        accountServiceProxy: new AccountServiceProxy(),
        AppSessionService: appSessionService,
        resetPasswordModel: new ResetPasswordModel(),
        ResetPasswordInput: new ResetPasswordInput(),
        saving: false,
        rules: {
          newPassword: [
            {
              required: true,
              message: this.l('PleaseEnterAnewPassword'),
            },
            {
              min: abp.setting.getInt('Abp.Zero.UserManagement.PasswordComplexity.RequiredLength'),
              message: this.l(
                'MinLength',
                abp.setting.get('Abp.Zero.UserManagement.PasswordComplexity.RequiredLength'),
              ),
              trigg: 'blur',
            },
            {
              max: 32,
              message: this.l('MaxLength', 32),
              trigg: 'blur',
            },
          ],
          passwordRepeat: [
            {
              validator: this.validateEqual,
              trigger: 'blur',
            },
          ],
        },
      };
    },
    created() {
      this.accountServiceProxy = new AccountServiceProxy(this.$apiUrl, this.$api);
      this.resetPasswordModel.resetCode = this.$route.query.resetCode as any;
      this.AppSessionService.changeTenantIfNeeded(this.parseTenantId(appSessionService.tenantId));
    },
    methods: {
      Backlogin() {
        this.$router.push('/account/login');
      },
      /**
       * 验证密码
       */
      validateEqual() {
        if (this.form.passwordRepeat === '') {
          return Promise.reject(this.l('PleaseInputThePasswordAgain'));
        } else if (this.form.passwordRepeat !== this.form.newPassword) {
          return Promise.reject(this.l('TwoInputsDonotMatch'));
        } else {
          return Promise.resolve();
        }
      },
      save(e) {
        e.preventDefault();
        (this.$refs.formRef as any).validate().then(() => {
          this.saving = true;
          this.ResetPasswordInput.resetCode = this.resetPasswordModel.resetCode;
          this.ResetPasswordInput.newPassword = this.form.newPassword;
          this.ResetPasswordInput.confirmPassword = this.form.passwordRepeat;
          this.accountServiceProxy
            .resetPassword(this.ResetPasswordInput)
            .then((result: ResetPasswordOutput) => {
              if (result.canLogin) {
                this.$router.push('account/login');
                return;
              }
            })
            .finally(() => {
              this.saving = false;
            });
        });
      },
      parseTenantId(tenantIdAsStr?: number): number {
        let tenantId = !tenantIdAsStr ? undefined : parseInt(tenantIdAsStr);
        if (tenantId === NaN) {
          tenantId = undefined;
        }

        return tenantId!;
      },
    },
  });
</script>
